<template>
  <view>
    <custom-navigation title="发送短信">
    </custom-navigation>
    <view class="white-card margin">
      <view class="card-title">
        发送概况
      </view>
      <view class="count-box">
        <view class="count-item">
          <view class="number">
            {{taocanInfo.total||'-'}}
          </view>
          <view class="label">
            短信总数
          </view>
        </view>
        <view class="count-item">
          <view class="number">
            {{taocanInfo.used||'-'}}
          </view>
          <view class="label">
            已发送数量
          </view>
        </view>
        <view class="count-item">
          <view class="number">
            {{taocanInfo.remain||'-' }}
          </view>
          <view class="label">
            剩余数量
          </view>
        </view>
      </view>
    </view>
    <view class="white-card padding">
      <view class="card-title">
        短信文案
      </view>
      <view class="form-content">
        <view class="form-item">
          <view class="label">
            <text class="text-red">*</text> 类型
          </view>
          <u-radio-group v-model="type" @change="typeChange">
            <view class="radio-item" v-for="item in templateInfo">
              <u-radio activeColor="#38C09E" shape="square" :name="item.name">
                {{item.name}}
              </u-radio>
            </view>
          </u-radio-group>
        </view>
        <view class="form-item" v-if="curType&&curType.scenes">
          <view class="label">
            <text class="text-red">*</text>场景
          </view>
          <u-radio-group v-model="scene" @change="sceneChange">
            <view class="radio-item" v-for="item in curType.scenes">
              <u-radio activeColor="#38C09E" shape="square" :name="item.name">
                {{item.name}}
              </u-radio>
            </view>
          </u-radio-group>
        </view>
        <view class="form-item" v-if="curScene&&curScene.subs">
          <view class="label">
          </view>

          <u-radio-group v-model="holiday" @change="holidayChange">
            <view class="radio-item" v-for="item in curScene.subs">
              <u-radio activeColor="#38C09E" shape="square" :name="item.name">
                {{item.name}}
              </u-radio>
            </view>
          </u-radio-group>
        </view>
        <view class="form-item label-top" v-if="curScene&&curScene.templates">
          <view class="label">
            <text class="text-red">*</text>模板内容（只限单选）
          </view>
          <u-radio-group v-model="tempID" @change="tempChange">
            <view class="radio-item" v-for="item in curScene.templates">
              <u-radio activeColor="#38C09E" shape="square" :name="item.templateId">
                {{item.content}}
              </u-radio>
            </view>
          </u-radio-group>
        </view>
        <view class="form-item label-top" v-else-if="curSub&&curSub.templates">
          <view class="label">
            <text class="text-red">*</text>模板内容（只限单选）
          </view>
          <u-radio-group v-model="tempID" @change="tempChange">
            <view class="radio-item" v-for="item in curSub.templates">
              <u-radio activeColor="#38C09E" shape="square" :name="item.templateId">
                {{item.content}}
              </u-radio>
            </view>
          </u-radio-group>
        </view>
        <view class="" v-if="contentConfig">
          <view class="form-item" v-for="item in contentConfig" v-if="item.name!=='门店名称'">
            <view class="label">
              <text class="text-red">*</text>{{item.name}}
            </view>
            <input type="number" v-model="item.value" class="input-box" v-if="item.type=='int'">
            <input type="digit" v-model="item.value" class="input-box" v-if="item.type=='float'">
            <input type="text" v-model="item.value" class="input-box" v-else-if="item.type=='text'">
            <view class="value input-box" @click="showCalendar=!showCalendar" v-else-if="item.type=='date_range'">
              <text v-if="item.value">{{item.value}}</text>
              <text v-else class="text-gray">选择起止日期</text>
              <u-calendar v-model="showCalendar" :mode="'range'" max-date="2099-12-31"
                @change="(e)=>item.value=e.startDate+'至'+e.endDate">
              </u-calendar>
            </view>

          </view>
        </view>
      </view>
      <view class="text-center" v-if="tempID&& taocanInfo&&taocanInfo.smsUseTitle&&taocanInfo.smsUseAgreement">
        <u-checkbox shape="circle" active-color="#38C09E" v-model="confirmAgreement" name="confirmAgreement">我已同意并阅读
        </u-checkbox> 
        <text class="text-green" @click="showAgreement">《短信通知功能使用协议》</text>
        <!-- <text class="text-green" @click="showAgreement">《{{taocanInfo.smsUseTitle}}》</text> -->
      </view>
    </view>

    <view class="button-box">
      <button class="button" @click="sendMsg()">确认发送</button>
    </view>
    <!--    <u-modal v-model="showConfirmText" v-if="taocanInfo.smsUseAgreement" :title="''">
      <view class="" style="max-height: 60vh;padding:0 10px ;overflow-y: scroll;">
        <rich-text :nodes="taocanInfo.smsUseAgreement"></rich-text>
        <view v-html="taocanInfo.smsUseAgreement"></view>
      </view>
    </u-modal> -->
    <u-modal v-model="showPwdDialog" title="请输入密码" show-cancel-button @confirm="confirmPWD">
      <view class="slot-content margin">
        <u-input v-model="vipPwd" type="password" :border="true" placeholder="请输入登录账号密码" />
        <text class="placeholder">注：请输入登录账号密码</text>
      </view>
    </u-modal>
  </view>
</template>

<script>
  import {
    apiPost
  } from '@/common/api/api.js'
  import dsBridge from 'dsbridge'
  export default {
    data() {
      return {
        showConfirmText: false,
        confirmAgreement: false,
        showCalendar: false,
        type: "",
        scene: "",
        holiday: "",
        tempID: "",
        startDate: '',
        endDate: "",
        discount: '',
        payAmount: null,
        discountAmount: null,
        taocanInfo: {},
        templateInfo: [],
        howManyYears: null,
        storeNo: '',
        mobiles: "",
        contentConfig: [],
        showPwdDialog:false,
        vipPwd:""
      };
    },
    computed: {
      curSub() {
        if (this.curScene?.subs) {
          return this.curScene.subs.find(item => item.name === this.holiday)
        }
      },
      curScene() {
        if (this.curType?.scenes) {
          return this.curType.scenes.find(item => item.name === this.scene)
        }
      },
      curType() {
        return this.templateInfo.find(item => item.name === this.type)
      },
      shengyu() {
        if (this.taocanInfo.total && this.taocanInfo.used) {
          return this.taocanInfo.total - this.taocanInfo.used
        }
        return '-'
      },
      curTemplate() {
        if (this.tempID) {
          if (this.curScene && this.curScene.templates) {
            return this.curScene.templates.find(e => e.templateId === this.tempID)
          } else if (this.curSub && this.curSub.templates) {
            return this.curSub.templates.find(e => e.templateId === this.tempID)
          }
        }
      },
    },
    methods: {
      async confirmPWD() {
        if (!this.vipPwd) {
          uni.showToast({
            title: '请输入登录密码',
            icon: 'none'
          })
          return
        }
        const url = `/sso/operate/srvls_send_pwd_confirm`
        const req = [{
          "serviceName": "srvls_send_pwd_confirm",
          "data": [{
            "pwd": this.vipPwd
          }]
        }]
        const res = await apiPost(url, req)
        if (res?.response?. [0]?.response?.confirm_code === 'SUCCESS') {
          this.sendMsg(true)
          // uni.navigateTo({
          //   url: `/pages/vip/send-msg?mobiles=${this.mobiles.toString()}`
          // })
          // return true
        } else {
          uni.showToast({
            title: '密码错误！',
            icon: 'none',
            duration: 3000
          })
          this.vipPwd = ''
          this.showPwdDialog = true
          return false
        }
      },
      
      showAgreement() {
        // this.showConfirmText=true
        uni.navigateTo({
          url: `./agreement?text=${encodeURIComponent(this.taocanInfo.smsUseAgreement)}&title=${encodeURIComponent(this.taocanInfo?.smsUseTitle)}`
        })
      },
      sendMsg(isValid) {
        if (this.taocanInfo?.smsUseTitle && this.taocanInfo.smsUseAgreement) {
          if (this.confirmAgreement == false) {
            uni.showToast({
              title: `请阅读并同意下方协议`,
              icon: 'none'
            })
            return
          }
        }
        const data = {
          "store_no": "",
          "mobiles": this.mobiles,
          "templateId": this.tempID,
          "sceneId": this.curScene.id,
          "subName": "",
          "params": []
        }
        if (this.curSub?.name) {
          data.subName = this.curSub?.name
        }
        if (this.curType.name) {
          data.name = this.curType?.name
        }
        if (this.curScene.id) {
          data.sceneId = this.curScene?.id
        }
        // "name": "关怀短信",
        //       "subName": "节日问候",
        //       "sceneId": "6"
        if (!this.tempID) {
          uni.showToast({
            title: '请选择模板内容',
            icon: 'none'
          })
          return
        }
        if (Array.isArray(this.contentConfig) && this.contentConfig.length > 0) {
          let valid = 0;
          let length = this.contentConfig.length;
          this.contentConfig.forEach((item, index) => {
            if (!item.value) {
              if (valid < index) {
                return
              }
              uni.showToast({
                title: `请${item.type==='date_range'?'选择':'输入'}${item.name}`,
                icon: 'none'
              })
            } else {
              valid++
            }
          })
          if (valid < length) {
            return
          } else {
            data.params = this.contentConfig.map(item => item.value)
          }
        }
        if(this.mobiles.length>1&&isValid!==true){
          this.showPwdDialog = true
          return
        }
        const url = `/retail/operate/srvmkt_note_send`
        const req = [{
          "serviceName": "srvmkt_note_send",
          "data": [data]
        }]
        apiPost(url, req).then(res => {
          console.log(res);
          if (res?.state == 'SUCCESS') {
            uni.showModal({
              title: '提示',
              content: '已经成功发送！',
              showCancel: false,
              success: (res) => {
                if (res.confirm) {
                  if (getCurrentPages().length <= 2) {
                    dsBridge.call("back")
                  }else{
                    uni.navigateBack()
                  }
                }
              }
            })
          } else {
            uni.showToast({
              title: res.resultMessage,
              icon: 'none'
            })
          }
        })
      },
      templateSelect() {
        const url = `/retail/select/srvmkt_package_scene_select`
        const req = {
          "serviceName": "srvmkt_package_scene_select",
        }
        apiPost(url, req).then(res => {
          if (res?.state === 'SUCCESS') {
            this.templateInfo = res.data
            this.setDefaultChecked()
          }
        })
      },
      async taocanSelect() {
        // 套餐查询
        const url = `/retail/select/srvmkt_package_select`
        const req = {
          "serviceName": "srvmkt_package_select",
          "condition": []
        }
        if (this.storeNo) {
          req.condition = [{
            "colName": "store_no",
            "ruleType": "eq",
            "value": this.storeNo
          }]
        }
        const res = await apiPost(url, req)
        if (res?.state === 'SUCCESS') {
          this.taocanInfo = res.data
        }
      },
      changeDateRange(e) {
        this.startDate = e.startDate
        this.endDate = e.endDate
      },
      tempChange(e) {
        if (this.curTemplate?.contentConfig && typeof this.curTemplate.contentConfig == 'string') {
          const contentConfig = JSON.parse(this.curTemplate.contentConfig)
          this.contentConfig = contentConfig.map(item => {
            item.value = ''
            if (item.name === '门店名称') {
              item.value = `${this.taocanInfo?.store_name}`
            }
            return item
          })
        }
      },
      holidayChange(e) {
        console.log(e);
        if (Array.isArray(this.curSub?.templates) && this.curSub?.templates.length > 0) {
          this.tempID = this.curSub?.templates[0].templateId
          this.tempChange()
        }
      },
      sceneChange(e) {
        console.log(e);
        this.contentConfig = []
        if (Array.isArray(this.curScene?.templates) && this.curScene?.templates.length > 0) {
          this.tempID = this.curScene?.templates[0].templateId
          this.tempChange()
        }
      },
      typeChange(e) {
        console.log(e);
        this.setDefaultChecked(e)
      },
      setDefaultChecked(name) {
        let resData = this.templateInfo
        if (Array.isArray(resData) && resData.length > 0) {
          let childData = resData[0]
          if (name) {
            let data = resData.find(e => e.name === name)
            if (data?.name) {
              childData = data
            }
          }
          this.type = childData.name
          if (Array.isArray(childData?.scenes) && childData?.scenes.length > 0) {
            this.scene = childData?.scenes[0].name
            if (Array.isArray(childData?.scenes[0].subs) && childData?.scenes[0].subs.length > 0) {
              this.holiday = childData?.scenes[0].subs[0].name
              if (Array.isArray(childData?.scenes[0].subs[0].templates) && childData?.scenes[0].subs[0]
                .templates.length > 0) {
                this.tempID = childData?.scenes[0].subs[0].templates[0].templateId
                this.tempChange()
              }
            } else if (Array.isArray(childData?.scenes[0].templates) && childData?.scenes[0].templates
              .length > 0) {
              this.tempID = childData?.scenes[0].templates[0].templateId
              this.tempChange()
            }
          }
        }
      },
    },
    onLoad(option) {
      if (option.mobiles) {
        this.mobiles = option.mobiles.split(',')
      }
      if (option.storeNo) {
        this.storeNo = option.storeNo
      }
      this.taocanSelect().then(() => {
        this.templateSelect()
      })
    }
  }
</script>

<style lang="scss" scoped>
  .text-green {
    color: #38C09E;
  }

  .text-center {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .white-card {
    background-color: #fff;
    padding: 20px 0;

    &.margin {
      margin: 10px;
      border-radius: 5px;
    }

    &.padding {
      padding: 20px 10px;
    }

    .card-title {
      padding: 0 10px;
      position: relative;
      margin-left: 10px;

      &::after {
        position: absolute;
        background-color: #BBBBBB;
        content: '';
        left: 0;
        width: 2px;
        height: 100%;
      }
    }

    .count-box {
      display: flex;
      justify-content: space-around;

      .count-item {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        margin: 10px 0;
        position: relative;

        &::after {
          content: '';
          width: 1px;
          background-color: #ccc;
          height: 100%;
          right: 0;
          position: absolute;
        }

        &:last-child {
          &::after {
            content: none;
          }
        }

        .number {
          color: #FF6955;
          font-size: 30px;
        }

        .label {
          color: #9F9D9D;
          margin-top: 10px;
        }
      }
    }
  }

  .form-content {
    padding: 10px;
  }

  .form-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;

    &.label-top {
      flex-direction: column;
      align-items: flex-start;

      .radio-item {
        width: 100%;
        padding-left: 10px;
      }

    }

    .text-red {
      color: #FF6955;
      margin-right: 2px;
    }

    .label {
      min-width: 80px;
    }

    .radio-item {
      min-width: 80px;
    }

    .input-box {
      width: 100%;
      height: 34px;
      line-height: 34px;
      border: 1px solid #eee;
      padding: 0 10px;

      .text-gray {
        color: #666;
      }
    }
  }

  .button-box {
    margin-top: 20px;
    padding: 20px 0;
    background-color: #fff;
  }

  .button {
    background-color: #38C09E;
    color: #fff;
    border-radius: 20px;
    width: 80%;

    &::after {
      border-color: #38C09E;
    }
  }

  .custom-modal {
    background-color: rgba(0, 0, 0, 0.5);
    width: 100vw;
    height: 100vh;
    z-index: 999;
    display: flex;
    align-items: center;
    justify-content: center;
    position: fixed;
    top: 0;
    left: 0;

    .custom-modal-content {
      width: 80vw;
      height: 60vh;
      overflow-y: scroll;
      background-color: #fff;
      padding: 20rpx;
      border-radius: 10rpx;
    }
  }
  .margin {
    margin: 10px;
  }
  
</style>
